﻿// ------------------------------------------------------------------
// DO NOT REMOVE THIS LINES IN ANY TIMES WILL BE.
// Original author: agehack
// Project name: Putingun
// ------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Drawing;
using System.Windows.Interop;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.IO;
using Putingun.PVDEngine;
using Agehack;
namespace Putingun
{
    public partial class App : System.Windows.Application
    {
        public const string VersionMark = "0.1";
        private const string C_PROCESS_NAME = "putingun";

        #region Запуск (валидатор запуска)
        public static void OnLoadDone(wndMain mainWindow)
        {
            MainWindow = mainWindow;
            ToggleTrayIcon();
        }
        private void OnStartup(object sender, StartupEventArgs e)
        {
            // FIXME здесь можно получить командную строку процесса
            try
            {
                if (!CheckValidStartup())
                    Exit();
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message,
                    "Putingun failed to validate startup", MessageBoxButton.OK,
                     MessageBoxImage.Error);
            }
        }
        public static bool CheckValidStartup()
        {
            // Проверить на имя *.exe файла
            FileInfo exe = new FileInfo(
                System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
            if (exe.Name.ToLower()
                .Replace(".vshost", String.Empty) !=          // DEBUG
                C_PROCESS_NAME + ".exe")
                throw new System.Security.SecurityException(
                    "You have to rename executable file to \"" + C_PROCESS_NAME + ".exe\" and try again.");
            
            // Проверить на multi-instanced
            if (InstanceControlTool.CheckAnyAnotherInstancesRunning(true))
                return false;   // если это не единственный запущенный экземпляр приложения

            return true;
        }
        #endregion
        public new static void Exit()
        {
            if (TrayIcon != null)
                ToggleTrayIcon();
            System.Windows.Application.Current.Shutdown(0);
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
        public static void ToggleMainWindow()
        {
            if (MainWindow.WindowState == WindowState.Normal)
                MainWindow.WindowState = WindowState.Minimized;
            else MainWindow.WindowState = WindowState.Normal;
        }
        public static void ToggleTrayIcon()
        {
            if (TrayIcon == null)
            {
                TrayIcon = new NotifyIcon();
                TrayIcon.Icon = AppTools.ImageToIcon(Putingun.Properties.Resources.ICON);
                TrayIcon.Text = "Путинвзрываетдома";
                TrayIcon.DoubleClick += new EventHandler(TrayIcon_DoubleClick);
                TrayIcon.ContextMenuStrip = (new frmForm()).trayContextMenu;
                TrayIcon.Visible = true;
            }
            else
            {
                TrayIcon.Visible = false;
                TrayIcon.Dispose();
                TrayIcon = null;
            }
        }
        static void TrayIcon_DoubleClick(object sender, EventArgs e)
        {
            ToggleMainWindow();
        }

        public new static wndMain MainWindow = null;
        public static PvdUserSession User = null;
        public static PvdAttackTargetInfo Target = PvdAttackTargetInfo.Default();
        public static NotifyIcon TrayIcon = null;
        public static bool UserIsAuthorized { get { return User != null && User.isAuthorized; } }
    }
    public static class AppTools
    {
        public static ImageSource ToImageSource(Icon icon)
        {
            Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();

            ImageSource wpfBitmap = Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            if (!DeleteObject(hBitmap))
            {
                throw new Exception();  // Memory leak
            }

            return wpfBitmap;
        }
        public static ImageSource ToImageSource(Bitmap bitmap)
        {
            var hbitmap = bitmap.GetHbitmap();
            try
            {
                var imageSource = Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty,
                    BitmapSizeOptions.FromWidthAndHeight(bitmap.Width, bitmap.Height));

                return imageSource;
            }
            finally
            {
                DeleteObject(hbitmap);
            }
        }
        public static Icon ImageToIcon(Image i)
        {
            Bitmap bmp = new Bitmap(i);
            System.IntPtr iconHandle = bmp.GetHicon();    
            return Icon.FromHandle(iconHandle);
        }

        [DllImport("gdi32.dll", SetLastError = true)]
        private static extern bool DeleteObject(IntPtr hObject);
    }
}
